package com.meida.module.arc.provider.util;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author zyf
 */
public class WordUtils {

    public static void wordToImage(String wordPath,String imagePath) throws Exception {
        try {
            // 读取Word文档
            XWPFDocument document = new XWPFDocument(new FileInputStream(wordPath));
            // 获取文档中所有段落
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            // 遍历所有段落
            for (XWPFParagraph paragraph : paragraphs) {
                // 创建一个空白的图片
                BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
                // 获取段落的运行属性
                List<XWPFRun> runs = paragraph.getRuns();
                // 遍历段落的运行属性
                for (XWPFRun run : runs) {
                    // 提取运行属性的文本内容并将其写入图片
                    String text = run.getText(0);
                    if (text != null) {
                        Graphics2D graphics = image.createGraphics();
                        FontRenderContext fontRenderContext = graphics.getFontRenderContext();
                        String font = run.getFontFamily();
                        int fontSize = run.getFontSize();
                        graphics.setFont(new Font(font, Font.PLAIN, fontSize));
                        GlyphVector glyphVector = graphics.getFont().createGlyphVector(fontRenderContext, text);
                        Shape textShape = glyphVector.getOutline();
                        graphics.dispose();
                        // 创建图片文件
                        File imageFile = new File(imagePath+"output/image.png");
                        imageFile.getParentFile().mkdirs();
                        // 将文本内容绘制到图片文件
                        BufferedImage textImage = new BufferedImage(textShape.getBounds().width, textShape.getBounds().height, BufferedImage.TYPE_INT_ARGB);
                        Graphics2D textGraphics = textImage.createGraphics();
                        textGraphics.setColor(Color.BLACK);
                        textGraphics.fill(textShape);
                        textGraphics.dispose();
                        // 将图片文件保存到磁盘
                        ImageIO.write(textImage, "png", new FileOutputStream(imageFile));
                    }
                }
            }
            // 关闭Word文档
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
